package com.starblink.android.guang

import android.app.Application
import com.starblink.android.basic.config.showTrackLogDss
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.util.AppStateTracker
import com.starblink.android.guang.push.FCMUtils
import com.starblink.basic.log.SKLogger
import com.starblink.basic.storage.SkStorage
import com.starblink.rocketreserver.OutletsBrandExposeClearQuery
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.joda.time.DateTime

/**
 * Created by dusensong on 2023/5/5.
 */
object GuangAppStateManager {
    private var appLaunchTime: Long = 0 //APP启动时间
    private var appTurnIntoForegroundTime: Long = 0 //APP每次进入前台时间

    fun init(application: Application) {
        AppStateTracker.track(
            application = application,
            appLaunch = { appLaunch() },
            appTurnIntoForeground = { appTurnIntoForeground() },
            appTurnIntoBackGround = { appTurnIntoBackGround() },

            )
    }

    private fun appLaunch() {
        appLaunchTime = DateTime.now().millis
        appTurnIntoForegroundTime = appLaunchTime

        outletsBrandExposeClear()

//        1. 10192.0 在40001之前报
        //开机屏splash
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.pageExposure.value,
                spmCnt = GTrackerAssistUtils.fetchPageValue(SpmPageDef.PageSplash),
                params = mapOf()
            )
        )

        SKLogger.e("dss", "埋点：APP启动", showTrackLogDss)
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.appLifeCycle.value,
                spmCnt = GTrackerAssistUtils.fetchElementValue(0, SpmElementDef.AppLaunch),
            )
        )
        //多次修改 最好确定其触发条件是第一次下载打开或者卸载重装
        firstLaunchAppReport()
    }

    /**
     * outlets品牌曝光数据清除
     * @note 异步执行
     */
    fun outletsBrandExposeClear() {
        SKLogger.e("dss", "outletsBrandExposeClear")
        CoroutineScope(Dispatchers.IO).launch {
            SkGqlClient.skQuery(
                OutletsBrandExposeClearQuery()
            )?.data?.outletsBrandExposeClear?.let {
                SKLogger.e("dss", "outlets品牌曝光数据清除成功", FCMUtils.showLog)
            } ?: SKLogger.e("dss", "outlets品牌曝光数据清除失败", FCMUtils.showLog)
        }
    }

    // 首次安装延迟倒计时
    private const val firstLaunch = "AF_FIRST_LAUNCH"

    //首次安装上报
    private fun firstLaunchAppReport() {
        if (!SkStorage.getBoolean(firstLaunch, false)) {
            SkStorage.put(firstLaunch, true)
            SpmTrackHandler.addSingleTrackData(
                SkAntEntity(
                    event = TrackEvent.appLifeCycle.value,
                    spmCnt = GTrackerAssistUtils.fetchElementValue(
                        0,
                        SpmElementDef.AppFirstLaunch
                    ),
                )
            )
        }
    }


    fun trackAppExist() {
        SKLogger.e("dss", "埋点：APP退出", showTrackLogDss)
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.appLifeCycle.value,
                spmCnt = GTrackerAssistUtils.fetchElementValue(0, SpmElementDef.AppExit),
                spmPrev = GTrackerAssistUtils.fetchElementValue(0, SpmElementDef.AppLaunch),
                params = mapOf("launchTime" to "${DateTime.now().millis - appLaunchTime}")
            )
        )
    }

    private fun appTurnIntoForeground() {
        appTurnIntoForegroundTime = DateTime.now().millis

        SKLogger.e("dss", "埋点：APP从后台返回", showTrackLogDss)
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.appLifeCycle.value,
                spmCnt = GTrackerAssistUtils.fetchElementValue(0, SpmElementDef.AppEnterForeground),
            )
        )
    }

    private fun appTurnIntoBackGround() {
        SKLogger.e("dss", "埋点：APP切换至后台", showTrackLogDss)
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.appLifeCycle.value,
                spmCnt = GTrackerAssistUtils.fetchElementValue(0, SpmElementDef.AppEnterBackground),
                spmPrev = GTrackerAssistUtils.fetchElementValue(
                    0,
                    SpmElementDef.AppEnterForeground
                ),
                params = mapOf("launchTime" to "${DateTime.now().millis - appTurnIntoForegroundTime}")
            )
        )
    }
}